<?php
namespace App\Service;

use Illuminate\Support\Facades\Redis as Redis;

use App\Models\ConfigureFunction;

use App\Models\Mall\MallMaster;

use App\Models\Goods\GoodsSale;

use App\Models\Goods\GoodsMaster;  //商品主表

use App\Service\PromotionService;

use App\Models\Bill\BillUsePromotion; //商品促销会员购买记录表

use App\Models\Goods\GoodsStore;

class CartService
{

    /**
     * 获取购物车数据
     * @param $arg_array
     * @return array
     */
    public static function getCartInfo( $cart_name = 'shop_cart', $pcustID = 0, $auto_code = null )
    {

        if ( empty($auto_code) ) {
            if (!$pcustID) {
                $auto_code = session_id() . $cart_name;
            } else {
                $auto_code = $cart_name . '_' . $pcustID;
            }
        }

        $bill_array = json_decode(Redis::get($auto_code), true);

        if (!$bill_array) {
            $bill_array = self::createCartStructure($cart_name);
        }

        return $bill_array;

    }

    /**
     * 获取购物车数据
     * @param $arg_array
     * @return array
     */
    public static function setCartInfo( $bill_array, $cart_name = 'shop_cart', $pcustID = 0, $auto_code = null )
    {

        if ( empty($auto_code) ) {
            if (!$pcustID) {
                $auto_code = session_id() . $cart_name;
            } else {
                $auto_code = $cart_name . '_' . $pcustID;
            }
        }

        Redis::setex($auto_code, 360000, json_encode($bill_array,true));

        return $bill_array;

    }

    /**
     * 获取购物车数据
     * @param $arg_array
     * @return array
     */
    private static function createCartStructure( $cart_name = 'shop_cart' )
    {

        $master = array(
            'bill_totalMoney' => 0,
            'bill_totalPaid' => 0,
            'bill_totalPoints' => 0,
            'bill_pointsPrice' => 0,
            'bill_subtract_money' => 0,
            'bill_points_money' => 0,
            'bill_balance_money' => 0,
            'bill_coupon_money' => 0,
            'bill_card_money' => 0,
            'bill_payable' => 0,
            'bill_total_amount' => 0,
            'billType' => 1,
            'remark' => null,
            'payPwd' => null,
            'payment_method_id' => null,
            'send_region_id' => 0
        );

        $bill_array = array(

            'bill_no' => null,

            'bill_status' => 0,

            //订单主表
            'master' => $master,

            //订单配置
            'bill_config_id' => 1,

            'change_time' => null,

            'message' => null,

            //订单商品
            'goods' => array(),

            //赠送优惠券
            'gift_coupon' => array(),

            //订单促销
            'bill_promotion' => array(),

            'activity_id' => 0

        );

        return $bill_array;

    }

    /**
     * 生成购物车商品数组结构
     * @param array $goods_array 商品数组
     * @param int $type
     * @return array
     */
    private static function createCartGoodsStructure( $goods_array, $type = 1 ) {

        if ($type == 1) {
            $goods_array['addPoints'] = 0;
            $goods_array['goods_groupID'] = 0;
            $goods_array['price'] = $goods_array['salePrice'];
        } else if ($type == 2 || $type == 3) {
            $goods_array['addPoints'] = 0;
            $goods_array['salePoints'] = 0;
            $goods_array['goodsWeight'] = 0;
            $goods_array['goodsLength'] = 0;
            $goods_array['goodsWidth'] = 0;
            $goods_array['goodsHeight'] = 0;
        } else if ($type == 4) {
            $goods_array['salePoints'] = 0;
        } else if ($type == 6 || $type == 5) {
            $goods_array['addPoints'] = 0;
            $goods_array['salePoints'] = 0;
        } else if ($type == 7) {
            $goods_array['addPoints'] = 0;
            $goods_array['salePoints'] = 0;
        } else if ($type == 8) {
            $goods_array['addPoints'] = 0;
            $goods_array['salePoints'] = 0;
        } else if ($type == 9) {
            $goods_array['addPoints'] = 0;
            $goods_array['price'] = $goods_array['unitPrice'];
        } else if ($type == 10 || $type == 11|| $type == 12 || $type == 13 || $type == 14) {
            $goods_array['addPoints'] = 0;
            $goods_array['salePoints'] = 0;
        }

        if (strstr($goods_array['spec'], '-默认')) {
            $goods_array['spec'] = '';
        }

        return array (
            'mainPostID' => $goods_array['mainPostID'],
            'goodsID' => $goods_array['goodsID'],
            'postID' => $goods_array['postID'],
            'goodsName' => $goods_array['goodsName'],
            'spec' => $goods_array['spec'],
            'goods_amount' => $goods_array['goods_amount'],
            'salePrice' => $goods_array['salePrice'],
            'price' => $goods_array['price'],
            'recordPrice' => $goods_array['recordPrice'],
            'addPoints' => $goods_array['addPoints'],
            'salePoints' => $goods_array['salePoints'],
            'goodsWeight' => $goods_array['goodsWeight'],
            'goodsRate'=>$goods_array['goodsRate'],
            'goods_from' => $type,
            'goods_groupID' => $goods_array['goods_groupID'],
            'goods_status' => 1,
            'is_buy' => 1,      //是否购买：0、不购买    1、暂时购买
            'img_link' => isset($goods_array['img_link']) ? $goods_array['img_link'] : '',
            'link' => isset($goods_array['link']) ? $goods_array['link'] : '',
            'wap_link' => isset($goods_array['wap_link']) ? $goods_array['wap_link'] : '',
            'product_code' => $goods_array['product_code'],
            'product_spec' => $goods_array['product_spec'],
            'marketPrice' => $goods_array['marketPrice'],
            'supplier_id' => $goods_array['supplier_id'],
            'promotion' => null,
            'promotion_id' => 0,
            'goodsType' => isset($goods_array['goodsType'])?$goods_array['goodsType']:1,
            'virtual_id' => isset($goods_array['virtual_id'])?$goods_array['virtual_id']:0,
            'virtual_name' =>  isset($goods_array['virtual_name'])?$goods_array['virtual_name']:'',
            'virtual_type' =>  isset($goods_array['virtual_type'])?$goods_array['virtual_type']:1,
            'time_slot_id' =>  isset($goods_array['time_slot_id'])?$goods_array['time_slot_id']:0,
        );

    }


    /**
     * 获取购物车商品数量
     * @return int
     */
    public static function getCartGoodsAmount($session_id) {
        $cart_amount = Redis::get('CART_AMOUNT_' . $session_id);
        return $cart_amount ? intval($cart_amount) : 0;
    }


    /**
     * 修改购物车商品数量
     * @param $goods_amount
     */
    private static function updateCartGoodsAmount( $session_id, $goods_amount ) {
        Redis::setex('CART_AMOUNT_' . $session_id, 360000000, $goods_amount);
    }


    /**
     * 加入购物车
     * @param $arg_array
     * @return array
     */
    public static function addGeneral( $arg_array )
    {

        $mallareaID = 0;
        $mallID = $arg_array['mallID'];
        $postID = $arg_array['postID'];
        $goods_amount = $arg_array['goods_amount'];
        $pcustID = $arg_array['pcustID'];
        $session_id = $arg_array['session_id'];
        $cart_name = isset($arg_array['cart_name']) ? $arg_array['cart_name'] : 'shop_cart';
        $platform = isset($arg_array['platform']) ? $arg_array['platform'] : 6;
        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        //门店区域
        if (ebsig_is_int($mallID)) {
            $mall_data = MallMaster::getCache($mallID);
            if ($mall_data)
                $mallareaID = $mall_data['mallareaID'];
        }

        //购物车信息
        $bill_array = self::getCartInfo($cart_name, $pcustID);

        if (!isset($bill_array['goods']['general'][$postID])) {

            $goods_array = GoodsSale::getCache($postID, $mallID);
            if (!$goods_array) {
                return array( 'code' => 404, 'message' => '商品信息没有找到' );
            }

            if ($goods_array['forsale'] == 0 || $goods_array['useFlg'] == 0) {
                return array( 'code' => 406, 'message' => '商品已下架' );
            }

            if ($goods_array['salePrice'] <= 0) {
                return array('code'=>400,'message'=>'商品已下架');
            }

            $goods_array['goods_amount'] = $goods_amount;
            $goods_array['img_link'] = $domain_url . $goods_array['goodsMainPic'];
            $cart_goods_array = self::createCartGoodsStructure( $goods_array, 1 );

        } else {
            $cart_goods_array = $bill_array['goods']['general'][$postID];
            $cart_goods_array['goods_amount'] += $goods_amount;
        }

        //查询商品主表信息
        $masterData = GoodsMaster::find($cart_goods_array['mainPostID']);
        if( !$masterData ) {
            return array( 'code' => 406, 'message' => '商品已下架' );
        }

        if ( ($masterData['WAP'] == 0 && in_array($platform, array(1, 2, '0'))) || ($masterData['PC'] == 0 && in_array($platform, array(3, 5))) || ($masterData['APP'] == 0 && $platform = 4) ) {
            return array( 'code' => 406, 'message' => '商品已下架' );
        }

        $goods_promotion = PromotionService::goods( array(
            'postID' => $cart_goods_array['postID'],
            'salePrice' => $cart_goods_array['salePrice'],
            'salePoints' => $cart_goods_array['salePoints'],
            'product_code' => $cart_goods_array['product_code'],
            'marketPrice' => $cart_goods_array['marketPrice'],
            'goods_amount' => $cart_goods_array['goods_amount'],
            'pcustID' => $pcustID,
            'mallareaID' => $mallareaID,
            'mallID' => $mallID,
            'platform' => $platform
        ));

        if ($goods_promotion['promotion']) {
            foreach($goods_promotion['promotion'] as $p) {
                if ( $p['promotion_type'] == 1 && $p['selected'] == 1 && $p['limit_num'] > 0) {
                    $cart_goods_array['goods_amount'] = $p['goods_amount'];
                    $promotion_use_data = BillUsePromotion::where(['promotion_id'=>$p['promotion_id'],'pcustID'=>$pcustID])->count();
                    if ( $promotion_use_data > 0 && ($promotion_use_data + $cart_goods_array['goods_amount'] > $p['limit_num'])) {
                        return array('code'=>400, 'message'=>'已超过商品限购数量，无法购买');
                    }
                }
            }
        }

        $enableSaleAmount = GoodsStore::search($cart_goods_array['product_code'], $cart_goods_array['product_spec'], $mallID);
        if ( $cart_goods_array['goods_amount'] > $enableSaleAmount ) {
            return array('code'=>400, 'message'=>'商品库存不足');
        }

        if ($cart_goods_array['goods_amount'] <= 0) {
            unset($bill_array['goods']['general'][$postID]);
        }

        $bill_array['goods']['general'][$postID] = $cart_goods_array;

        //保存购物车信息
        $bill_array['bill_config_id'] = 1;
        $bill_array['activity_id'] = 0;
        $bill_array['goods']['change_time'] = time();
        self::setCartInfo( $bill_array, $cart_name, $pcustID );
       
        //更新购物车数量
        $cart_goods_amount = self::getCartGoodsAmount($session_id);
        $cart_goods_amount += $goods_amount;
        self::updateCartGoodsAmount( $session_id, $cart_goods_amount );

        return array( 'code' => 200, 'message' => 'ok', 'data' => array( 'price' => $cart_goods_array['price'], 'cart_amount' => $cart_goods_amount ) );

    }


    /**
     * 立即购买
     * @param $arg_array
     * @return array
     */
    public static function nowBuy( $arg_array )
    {

        $mallareaID = 0;
        $mallID = $arg_array['mallID'];
        $postID = $arg_array['postID'];
        $goods_amount = $arg_array['goods_amount'];
        $auto_code = $arg_array['auto_code'];
        $pcustID = $arg_array['pcustID'];
        $cart_name = isset($arg_array['cart_name']) ? $arg_array['cart_name'] : 'now_buy';
        $platform = isset($arg_array['platform']) ? $arg_array['platform'] : 6;
        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        //门店区域
        if (ebsig_is_int($mallID)) {
            $mall_data = MallMaster::getCache($mallID);
            if ($mall_data)
                $mallareaID = $mall_data['mallareaID'];
        }

        $goods_array = GoodsSale::getCache($postID, $mallID);
        if (!$goods_array) {
            return array( 'code' => 404, 'message' => '商品信息没有找到' );
        }

        if ($goods_array['forsale'] == 0 || $goods_array['useFlg'] == 0) {
            return array( 'code' => 406, 'message' => '商品已下架' );
        }

        if ($goods_array['salePrice'] <= 0) {
            return array('code'=>400,'message'=>'商品已下架');
        }

        //购物车信息
        $bill_array = self::getCartInfo($cart_name, $auto_code);
        $bill_array['goods']['general'] = array();


        $goods_array['goods_amount'] = $goods_amount;
        $goods_array['img_link'] = $domain_url . $goods_array['goodsMainPic'];
        $goods_array['link'] = set_goods_link($goods_array['postID']);
        $goods_array['wap_link'] = set_wap_goods_link($goods_array['postID']);
        $cart_goods_array = self::createCartGoodsStructure( $goods_array, 1 );

        $goods_promotion = PromotionService::goods( array(
            'postID' => $cart_goods_array['postID'],
            'salePrice' => $cart_goods_array['salePrice'],
            'salePoints' => $cart_goods_array['salePoints'],
            'product_code' => $cart_goods_array['product_code'],
            'marketPrice' => $cart_goods_array['marketPrice'],
            'goods_amount' => $cart_goods_array['goods_amount'],
            'pcustID' => $pcustID,
            'mallareaID' => $mallareaID,
            'mallID' => $mallID,
            'platform' => $platform
        ));
        if ($goods_promotion['promotion']) {
            foreach($goods_promotion['promotion'] as $p) {
                if ( $p['promotion_type'] == 1 && $p['selected'] == 1 && $p['limit_num'] > 0) {
                    $cart_goods_array['goods_amount'] = $p['goods_amount'];
                    $promotion_use_data = BillUsePromotion::where(['promotion_id'=>$p['promotion_id'],'pcustID'=>$pcustID])->count();
                    if ( $promotion_use_data > 0 && ($promotion_use_data + $cart_goods_array['goods_amount'] > $p['limit_num'])) {
                        return array('code'=>400, 'message'=>'已超过商品限购数量，无法购买');
                    }
                }
            }
        }

        $enableSaleAmount = GoodsStore::search($cart_goods_array['product_code'], $cart_goods_array['product_spec'], $mallID);
        if ( $cart_goods_array['goods_amount'] > $enableSaleAmount ) {
            return array('code'=>400, 'message'=>'商品库存不足');
        }

        $bill_array['goods']['general'][0] = $cart_goods_array;

        //如果是虚拟商品
        if ($cart_goods_array['goodsType'] == 2 && ebsig_is_int($cart_goods_array['virtual_id'])) {
            $bill_array['bill_config_id'] = 2;
            $bill_array['activity_id'] = 2;
            $bill_array['billType'] = 10;
        } else {
            $bill_array['bill_config_id'] = 1;
            $bill_array['activity_id'] = 0;
            $bill_array['billType'] = 1;
        }

        self::setCartInfo( $bill_array, $cart_name, $pcustID, $auto_code );

        return array( 'code' => 200, 'message' => 'ok', 'data' => array( 'price' => $cart_goods_array['price'] ) );

    }

    /**
     * 加载购物车数据
     * @param null $auto_code
     * @param array $extend_data
     * @return array
     */
    public static function loadCart( $auto_code = null, $extend_data = array()  ) {

        //返回的购物车商品数组
        $return_array = array(
            'date' => date('Ymd'), //日期
            'totalPaid' => 0, //实售总金额
            'totalMoney' => 0, //商品总金额
            'totalPoints' => 0, //总获得积分
            'totalAddPoints' => 0, //总花费积分
            'goods_amount' => 0, //商品总数量
            'goods_promotion_amount' => 0, //商品促销活动优惠券金额
            'totalWeight' => 0, //商品总重量
            'bill_subtract_money' => 0, //订单促销立减金额
            'promotion_money' => 0, //总促销优惠金额
            'is_buy_total_amount' => 0, //选中商品数量
            'is_buy_total_sale_money' => 0, //选中商品总金额
            'is_buy_total_money' => 0 //选中商品的实售总金额
        );

        $mallareaID = 0;
        $cart_name = isset($extend_data['cart_name']) ? $extend_data['cart_name'] : 'shop_cart';
        $platform = $extend_data['platform'];
        $mallID = $extend_data['mallID'];
        $pcustID = $extend_data['userId'];

        //获取redis中的购物车数组
        $bill_array = self::getCartInfo($cart_name, $pcustID, $auto_code);

        //加钱换购重置
        if (isset($bill_array['exchange_goods']) && !empty($bill_array['exchange_goods'])) {
            $exchange_goods = $bill_array['exchange_goods'];
            $bill_array['exchange_goods'] = array();
        }

        //门店区域
        if (ebsig_is_int($mallID)) {
            $mall_data = MallMaster::find($mallID);
            if ($mall_data)
                $mallareaID = $mall_data['mallareaID'];
        }

        //商品数组，用来统计商品购买数量
        $c_goods_array = array();

        //订单促销商品数组，用于订单促销
        $orders_promotion_goods_array = array();

        //套装商品
        if ( isset($bill_array['goods']['group']) ) {

            foreach( $bill_array['goods']['group'] as $key=> $group) {

                $group['hasStock'] = 1;

                foreach($group['goods'] as $k=>$list) {
                    $list['hasStock'] = 1;

                    $sale_data = GoodsSale::getCache( $list['postID']);
                    if (!$sale_data || $sale_data['useFlg'] == 0 || $sale_data['forsale'] == 0) {
                        $list['hasStock'] = 0;
                        $group['hasStock'] =0;
                    }

                    //查询库存
                    $store = GoodsStore::search($list['product_code'], $list['product_spec'], $mallID);
                    $goods_count = $list['goods_amount'] * $group['group_amount'];
                    if ($store < $goods_count) {
                        $list['hasStock'] = 0;
                        $group['hasStock'] =0;
                    }
                    $group['goodsType'] = $list['goodsType'];
                    $group['goods'][$k] = $list;
                }

                if ( $group['hasStock'] == 0 ) {
                    $group['is_buy'] = 0;
                }

                foreach($group['goods'] as $k=>$list) {
                    $goods_amount = $list['goods_amount'] * $group['group_amount'];
                    if (isset($c_goods_array[$list['postID']])) {
                        $c_goods_array[$list['postID']] += $goods_amount;
                    } else {
                        $c_goods_array[$list['postID']] = $goods_amount;
                    }
                    $return_array['totalPoints'] += $list['salePoints'] * $goods_amount;
                    $return_array['totalWeight'] += $list['goodsWeight'] * $goods_amount;
                    $return_array['totalMoney'] += $list['salePrice'] * $goods_amount;
                    $return_array['totalPaid'] += $list['price'] * $goods_amount;
                    $return_array['goods_promotion_amount'] += ($return_array['totalMoney'] - $return_array['totalPaid']);
                    $return_array['goods_amount'] += $goods_amount;

                    if ($group['is_buy'] == 1 && $group['hasStock'] == 1) {
                        $return_array['is_buy_total_amount'] += $goods_amount;
                        $return_array['is_buy_total_sale_money'] += $goods_amount * $list['salePrice'];
                        $return_array['is_buy_total_money'] += round($goods_amount * $list['price'], 2);
                        $orders_promotion_goods_array[] = array(
                            'postID' => $list['postID'],
                            'price' => $list['price'],
                            'goods_amount' => $goods_amount,
                            'type' => 'group'
                        );
                    }
                    $group['goods'][$k] = $list;

                }

                $bill_array['goods']['group'][$key] = $group;

            }

            $return_array['group'] = $bill_array['goods']['group'];

        }

        //普通商品
        if (isset($bill_array['goods']['general'])) {

            foreach ($bill_array['goods']['general'] as $key => $goods) {

                //是否支持当前平台
                $goods['platform_support'] = 1;
                $goods['platform_support_msg'] = '';

                if ( isset($c_goods_array[$goods['postID']]) ) {
                    $goods_amount = $c_goods_array[$goods['postID']] + $goods['goods_amount'];
                } else {
                    $goods_amount = $goods['goods_amount'];
                }

                $goods_data = GoodsSale::getCache( $goods['postID'], $mallID);
                if (!$goods_data || $goods_data['useFlg'] == 0 || $goods_data['forsale'] == 0) {
                    unset($bill_array['goods']['general'][$key]);
                    continue;
                }

                //判断平台支持
                $masterData = GoodsMaster::find($goods['mainPostID']);
                if ($masterData) {
                    if (in_array($platform, array(1, 2, '0'))) {
                        if ($masterData['WAP'] != 1) {
                            $goods['platform_support'] = 0;
                        }
                    } else if (in_array($platform, array(3, 5))) {
                        if ($masterData['PC'] != 1) {
                            $goods['platform_support'] = 0;
                        }
                    } else if ($platform == 4) {
                        if ($masterData['APP'] != 1) {
                            $goods['platform_support'] = 0;
                        }
                    }
                    if ($masterData['PC'] == 1) {
                        $goods['platform_support_msg'] .= 'pc、';
                    }
                    if ($masterData['WAP'] == 1) {
                        $goods['platform_support_msg'] .= 'wap、';
                    }
                    if ($masterData['APP'] == 1) {
                        $goods['platform_support_msg'] .= 'app、';
                    }
                    if ($goods['platform_support_msg'] != '' && $goods['platform_support'] == 0) {
                        $goods['platform_support_msg'] = '仅在'
                            .rtrim($goods['platform_support_msg'], '、')
                            .'商城销售';
                    }
                }

                //更新购物车商品信息
                $goods['marketPrice'] = $goods_data['marketPrice'];
                $goods['salePrice'] = $goods_data['salePrice'];
                $goods['salePoints'] = $goods_data['salePoints'];
                $goods['hasStock'] = 1;

                //根据会员等级计算商品价格及积分，同时检查商品促销活动
                if ($cart_name != 'pf_shop_cart') {

                    //查询库存
                    $store = GoodsStore::search($goods['product_code'], $goods['product_spec'], $mallID);
                    if ($store < $goods_amount) {
                        $goods['is_buy'] = 0;
                        $goods['hasStock'] = 0;
                    }

                    $goods_promotion = PromotionService::goods( array(
                        'postID' => $goods['postID'],
                        'salePrice' => $goods['salePrice'],
                        'salePoints' => $goods['salePoints'],
                        'product_code' => $goods['product_code'],
                        'marketPrice' => $goods['marketPrice'],
                        'goods_amount' => $goods['goods_amount'],
                        'pcustID' => $pcustID,
                        'mallareaID' => $mallareaID,
                        'mallID' => $mallID,
                        'platform' => $platform,
                        'check' => 1,
                        'cust_promotion' => 1
                    ));

                    $goods['price'] = $goods_promotion['price'];
                    $goods['salePoints'] = $goods_promotion['salePoints'];
                    $goods['promotion'] = !empty($goods_promotion['promotion']) ? $goods_promotion['promotion'] : null;

                }

                $return_array['totalMoney'] += $goods['salePrice'] * $goods['goods_amount'];
                $return_array['totalPaid'] += $goods['price'] * $goods['goods_amount'];
                $return_array['totalPoints'] += $goods['salePoints'] * $goods['goods_amount'];
                $return_array['totalWeight'] += $goods['goodsWeight'] * $goods['goods_amount'];
                $return_array['goods_amount'] += $goods['goods_amount'];
                if ($goods['is_buy'] && $goods['platform_support']) {
                    $return_array['is_buy_total_amount'] += $goods['goods_amount'];
                    $return_array['is_buy_total_sale_money'] += $goods['salePrice'] * $goods['goods_amount'];
                    $return_array['is_buy_total_money'] += round($goods['price'] * $goods['goods_amount'], 2);
                    $return_array['goods_promotion_amount'] += ($return_array['is_buy_total_sale_money'] - $return_array['is_buy_total_money']);
                    $orders_promotion_goods_array[] = array(
                        'postID' => $goods['postID'],
                        'price' => $goods['price'],
                        'goods_amount' => $goods['goods_amount'],
                        'type' => 'general'
                    );
                }

                $bill_array['goods']['general'][$key] = $goods;

            }

            $return_array['general'] = $bill_array['goods']['general'];

        }

        //订单促销
        if (!empty($orders_promotion_goods_array) && $cart_name != 'pf_shop_cart') {

            $orders_promotion_array = PromotionService::orders( array(
                'pcustID' => $pcustID,
                'mallareaID' => $mallareaID,
                'mallID' => $mallID,
                'is_use_coupon' => 0,
                'platform' => $platform,
            ), $orders_promotion_goods_array );

            if ($orders_promotion_array && !empty($orders_promotion_array)) {

                foreach($orders_promotion_array as $p) {
                    //满足的促销
                    if ($p['is_meet'] == 1) {
                        if ($p['type'] == 1 || $p['type'] == 8) {
                            $return_array['totalPaid'] -= round($p['subtractMoney'] * $p['multiple'], 2);
                            $p['totalSubtractMoney'] = round($p['subtractMoney'] * $p['multiple'], 2);
                            $return_array['bill_subtract_money'] += round($p['subtractMoney'] * $p['multiple'], 2);

                        } else if ($p['type'] == 7) {
                            $p['exchange'] = array_values($p['exchange']);
                            foreach($p['exchange'] as $key=>$e) {
                                if (isset($exchange_goods[$p['promotion_id']]) && $exchange_goods[$p['promotion_id']]['postID'] == $e['postID']) {
                                    $bill_array['exchange_goods'][$p['promotion_id']] = array(
                                        'postID' => $e['postID'],
                                        'goods_amount' => $e['saleAmount']
                                    );
                                    $return_array['totalMoney'] += $e['price'] * $e['saleAmount'];
                                    $return_array['totalPaid'] += $e['exchange_price'] * $e['saleAmount'];
                                    $return_array['goods_amount'] += $e['saleAmount'];
                                    $return_array['is_buy_total_amount'] += $e['saleAmount'];
                                    $return_array['is_buy_total_sale_money'] += $e['price'] * $e['saleAmount'];
                                    $return_array['is_buy_total_money'] += round($e['exchange_price'] * $e['saleAmount'],2);
                                    $e['selected'] = 1;
                                    $p['exchange'][$key] = $e;
                                }
                            }
                        }
                    }
                    //促销重组方式(部分商品)
                    if (isset($p['merge']) && !empty($p['merge'])) {
                        $merge_list = array();
                        $goods_type = 1;
                        foreach($p['merge'] as $key=>$m) {
                            if (!isset($return_array['general'][$key]) || $return_array['general'][$key]['is_buy'] != 1)
                                continue;
                            $merge_list[$key] = $return_array['general'][$key];
                            $goods_type = $merge_list[$key]['goodsType'];
                            unset($return_array['general'][$key]);
                            if (empty($return_array['general']))
                                unset($return_array['general']);
                        }
                        $return_array['merge'][] = array(
                            'orders' => $p,
                            'list' => $merge_list,
                            'goods_type' => $goods_type
                        );
                    } else {
                        $return_array['bill'][] = $p;
                    }

                }

            }

        }

        $return_array['is_buy_total_money'] -= $return_array['bill_subtract_money'];
        $return_array['promotion_money'] = round($return_array['is_buy_total_sale_money'] - $return_array['is_buy_total_money'], 2);
        if ( $return_array['is_buy_total_money'] < 0 ) {
            $return_array['is_buy_total_money'] = '0.00';
        }

        if ( $return_array['promotion_money'] < 0 ) {
            $return_array['promotion_money'] = 0;
        }

        //更新购物车信息
        $bill_array['change_time'] = time();
        self::setCartInfo($bill_array,'shop_cart',$auto_code);

        //更新购物车商品数量
        self::updateCartGoodsAmount($extend_data['session_id'], $return_array['goods_amount']);

        if (empty($return_array)) {
            return array( 'code' => 406, 'message' => '您的购物车中没有商品，先去选购吧！' );
        }

        $return_array['totalPaid'] = number_format( $return_array['totalPaid'],2);
        $return_array['date'] = date('Y-m-d');

        return array('code' => 200, 'message' => 'ok', 'data' => $return_array);

    }

    /**
     * 删除购物车商品
     * @param int $postID 商品三级网购号
     * @param null $auto_code 自定义code
     * @param array $extend_data 扩展参数数组
     * @return array
     */
    public static function delGeneralGoods( $postID, $pcustID, $session_id, $extend_data = array() ) {

        $cart_name = isset($extend_data['cart_name']) ? $extend_data['cart_name'] : 'shop_cart';

        //购物车信息
        $bill_array = self::getCartInfo($cart_name, $pcustID);

        $goods_amount = 0;

        //商品已在购物车里
        if (isset($bill_array['goods']['general'][$postID])) {
            $goods_amount = $bill_array['goods']['general'][$postID]['goods_amount'];
            unset($bill_array['goods']['general'][$postID]);
        }

        if (empty($bill_array['goods']['general']))
            unset($bill_array['goods']['general']);

        //更新购物车信息
        $bill_array['change_time'] = time();
        self::setCartInfo( $bill_array, $cart_name, $pcustID );

        //更新购物车数量
        if ($cart_name != 'pf_shop_cart') {
            $cart_goods_amount = self::getCartGoodsAmount($session_id);
            $cart_goods_amount -= $goods_amount;
            self::updateCartGoodsAmount( $session_id, $cart_goods_amount );
        }

        return array( 'code' => 200, 'message' => 'ok' );

    }

    /**
     * 检查购物车数据
     * @param $bill_array
     * @param null $pcustID
     * @param int $mallID
     * @param int $platform
     * @return array
     */
    public static function checkCart($bill_array, $pcustID = 0, $mallID = 0, $platform = 0) {

        //查询门店设置
        $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall');
        $mallareaID = 0;

        //门店区域
        if ($is_choose_goods_by_mall) {
            if (ebsig_is_int($mallID)) {
                $mall_data = MallMaster::getCache($mallID);
                if ($mall_data)
                    $mallareaID = $mall_data['mallareaID'];
            }
        }

        if (isset($bill_array['goods']['general'])) {
            foreach($bill_array['goods']['general'] as $key=>$goods_data) {
                $goods_promotion = PromotionService::goods( array(
                    'postID' => $goods_data['postID'],
                    'salePrice' => $goods_data['salePrice'],
                    'salePoints' => $goods_data['salePoints'],
                    'product_code' => $goods_data['product_code'],
                    'marketPrice' => $goods_data['marketPrice'],
                    'goods_amount' => $goods_data['goods_amount'],
                    'pcustID' => $pcustID,
                    'mallareaID' => $mallareaID,
                    'mallID' => $mallID,
                    'platform' => '0'
                ));
                if (isset($goods_promotion['promotion'])) {
                    foreach($goods_promotion['promotion'] as $p) {
                        if ( $p['promotion_type'] == 1 && $p['selected'] == 1 && $p['limit_num'] > 0) {

                            $bill_use_promotion = BillUsePromotion::where(['promotion_id'=>$p['promotion_id'],'pcustID'=>$pcustID])->count();
                            if ( $bill_use_promotion > 0 && ($bill_use_promotion + $goods_data['goods_amount'] > $p['limit_num'])) {
                                return array('code'=>406, 'message'=>'商品['.$goods_data['goodsName'].']每人限购' . $p['limit_num'] . '件');
                            }
                        }
                    }
                }
            }
        }

        return array('code'=>200, 'message'=>'ok');

    }

    /**
     * 综合商品数组
     * @param array $bill_array 订单数组
     * @param null $pcustID 会员ID
     * @param int $shop_id 店铺id
     * @param int $platform 平台
     * @param int $check_type 结算类型
     * @return array
     */
    public static function goodsColligate($bill_array, $pcustID=null, $shop_id = 0, $platform = 0, $check_type = 1) {

        $bill_goods = $bill_array['goods'];

        $goods_array = array();

        //生成商品数组
        if ( isset($bill_goods['group']) && !empty($bill_goods['group']) ) {
            foreach($bill_goods['group'] as $group) {
                if (isset($group['is_buy']) && $group['is_buy'] == 0) {
                    continue;
                }
                foreach( $group['goods'] as $list ) {
                    if (($check_type == 2 && $list['goodsType'] != 3) || ($check_type == 1 && $list['goodsType'] == 3))
                        continue;
                    $goods_array[] = array(
                        'postID' => $list['postID'],
                        'price' => $list['price'],
                        'goodsAmount' => $group['group_amount']
                    );
                }
            }
        }

        if (isset($bill_goods['general']) && !empty($bill_goods['general'])) {

            //查询门店设置
            $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall');
            $mallareaID = 0;

            //门店区域
            if ($is_choose_goods_by_mall) {
                if (ebsig_is_int($shop_id)) {
                    $mall_data = MallMaster::getCache($shop_id);
                    if ($mall_data)
                        $mallareaID = $mall_data['mallareaID'];
                }
            }

            foreach ($bill_goods['general'] as $list) {
                if (isset($list['is_buy']) && $list['is_buy'] == 0)
                    continue;
                if (($check_type == 2 && $list['goodsType'] != 3) || ($check_type == 1 && $list['goodsType'] == 3))
                    continue;

                //商品促销
                $args_data = array(
                    'goods' => $list,
                    'pcustID' => $pcustID,
                    'mallareaID' => $mallareaID,
                    'mallID' => $shop_id,
                    'platform' => $platform,
                    'check' => 1,
                );
                $list = PromotionService::calculate_goods_price($args_data);
                $goods_array[] = array(
                    'postID' => $list['postID'],
                    'price' => $list['price'],
                    'goodsAmount' => $list['goods_amount']
                );
            }
        }

        if (isset($bill_goods['points']) && !empty($bill_goods['points'])) {
            foreach($bill_goods['points'] as $points) {
                $goods_array[] = array(
                    'postID' => $points['postID'],
                    'price' => $points['price'],
                    'goodsAmount' => $points['goods_amount']
                );
            }
        }

        if (isset($bill_goods['flashBuy'])) {
            foreach ( $bill_goods['flashBuy']['goods'] as $flashBuyData ){
                foreach($flashBuyData as $flashBuy){
                    $goods_array[] = array(
                        'postID' => $flashBuy['postID'],
                        'price' => $flashBuy['price'],
                        'goodsAmount' => $flashBuy['goods_amount']
                    );
                }
            }
        }

        if (isset($bill_goods['special']) && !empty($bill_goods['special'])) {
            foreach($bill_goods['special'] as $special){
                $goods_array[] = array(
                    'postID' => $special['postID'],
                    'price' => $special['price'],
                    'goodsAmount' => $special['goods_amount']
                );
            }
        }

        if (isset($bill_goods['flash']) && !empty($bill_goods['flash'])) {
            foreach($bill_goods['flash'] as $flash){
                $goods_array[] = array(
                    'postID' => $flash['postID'],
                    'price' => $flash['price'],
                    'goodsAmount' => $flash['goods_amount']
                );
            }
        }

        if (isset($bill_goods['pre_sale']) && !empty($bill_goods['pre_sale'])) {
            foreach($bill_goods['pre_sale'] as $pre_sale){
                $goods_array[] = array(
                    'postID' => $pre_sale['postID'],
                    'price' => $pre_sale['price'],
                    'goodsAmount' => $pre_sale['goods_amount']
                );
            }
        }

        if (isset($bill_goods['crowd'])) {
            foreach($bill_goods['crowd'] as $crowd) {
                $goods_array[] = array(
                    'postID' => $crowd['postID'],
                    'price' => $crowd['price'],
                    'goodsAmount' => $crowd['goods_amount']
                );
            }
        }

        if (isset($bill_goods['seckill']) && !empty($bill_goods['seckill'])) {
            foreach($bill_goods['seckill'] as $seckill){
                $goods_array[] = array(
                    'postID' => $seckill['postID'],
                    'price' => $seckill['price'],
                    'goodsAmount' => $seckill['goods_amount']
                );
            }
        }

        return $goods_array;

    }

}
